const editor1 = document.getElementById('editor1')
const editor2 = document.getElementById('editor2')
const jsonkey = 'jsonv'
const h = document.querySelector("#sync-active")
const c = document.querySelector("#sync-left")
const d = document.querySelector("#sync-right")
const u = document.querySelector("#load-left")
const f = document.querySelector("#load-right")
const m = document.querySelector("#save-left")
const p = document.querySelector("#save-right")
const g = document.querySelectorAll(".svg-sync");
let syncActive = true;

const leftOptions = {
  mode: 'code',
  modes: ['code', 'form', 'text', 'tree', 'view', 'preview'], // allowed modes
  onChangeText: (e) => {
    try {
      localforage.setItem(jsonkey,leftEditor.get())
        if (syncActive){
            console.log('左边'+e)
              rightEditor.updateText(e)
        }
    } catch (e) {}
  },
}
const rightOptions = {
  mode: 'tree',
  modes: [], // allowed modes
  onChangeText: (e) => {
    try {
      localforage.setItem(jsonkey,rightEditor.get())
        if (syncActive){
              console.log('右边'+e)
            leftEditor.updateText(e)
        }
    } catch (e) {}
  },
}
utools.onPluginEnter(({ code, type, payload, option }) => {
    if (type === 'regex'){
          leftEditor.updateText(payload);
          rightEditor.updateText(payload);
    }else {
        const e = {
                                array: [1, 2, 3],
                                boolean: !0,
                                null: null,
                                number: 123,
                                object: {
                                    a: "b",
                                    c: "d"
                                },
                                string: "Hello World"
                            };
                            leftEditor.set(e),
                                rightEditor.set(e)
    }

    });
const mode = window.location.search.substring(1)
const leftEditor = new JSONEditor(editor1, leftOptions)
const rightEditor = new JSONEditor(editor2, rightOptions)
async function init() {
  let json = ''
  try {
    try{
      // 获取url后面的json字符串
      if (!mode || mode === '') {
        json = await localforage.getItem(jsonkey) || json
      } else if ('none' === mode) {
        json = ''
      } else if ('clipboard' === mode) {
        chrome.runtime.sendMessage({}, function (response){
          json = response.clipboard;
          try {
            leftEditor.set(JSON.parse(json))
          } catch(e) { }
        });
        return
      }
    }catch(e) {
     json = await localforage.getItem(jsonkey) || json
    }
  } catch (e) { }
  if (json) { 
    leftEditor.set(json)
  } else {
    leftEditor.setText(json)
  }
}
init()

leftEditor.focus()
// 设置JSONEditor实例
window.JSONEditorInstance = leftEditor

//加载时设置默认字体大小
var font = parseInt(localStorage.getItem('jsonedit_fontsize'));
if (font < 0) {
	font = 15;
  localStorage.setItem('jsonedit_fontsize', font);
}
document.querySelector('.ace_editor').style.fontSize = font + 'px';


h.addEventListener("click", function(e) {
                            e.preventDefault();
                            // 切换syncActive的状态
                            syncActive = !syncActive;

                            // 根据syncActive的状态执行操作
                            if (syncActive) {
                                g.forEach(element => {
                                    element.classList.toggle("hidden");
                                });
                                c.disabled = true;
                                d.disabled = true;
                            } else {
                                g.forEach(element => {
                                    element.classList.toggle("hidden");
                                });
                                c.disabled = false;
                                d.disabled = false;
                            }
                        }),
                        c.addEventListener("click", (e => v(e, rightEditor, leftEditor))),
                        d.addEventListener("click", (e => v(e, leftEditor, rightEditor))),
                        u.addEventListener("click", (e => y(e, leftEditor))),
                        f.addEventListener("click", (e => y(e, rightEditor))),
                        m.addEventListener("click", (e => w(e, leftEditor))),
                        p.addEventListener("click", (e => w(e, rightEditor))),
                        function () {
                                syncActive = !0,
                                c.disabled = !0,
                                d.disabled = !0;
                            }();

// 下面是我瞎写的

  function v(e, t, n) {
                            if (!(this instanceof v))
                                throw new Error('JSONEditor constructor called without "new".');
                            var i = d();
                            if (-1 !== i && i < 9)
                                throw new Error("Unsupported browser, IE9 or newer required. Please install the newest version of your browser.");
                            t && (t.error && (console.warn('Option "error" has been renamed to "onError"'),
                                t.onError = t.error,
                                delete t.error),
                            t.change && (console.warn('Option "change" has been renamed to "onChange"'),
                                t.onChange = t.change,
                                delete t.change),
                            t.editable && (console.warn('Option "editable" has been renamed to "onEditable"'),
                                t.onEditable = t.editable,
                                delete t.editable),
                            t.onChangeJSON && ("text" === t.mode || "code" === t.mode || t.modes && (-1 !== t.modes.indexOf("text") || -1 !== t.modes.indexOf("code"))) && console.warn('Option "onChangeJSON" is not applicable to modes "text" and "code". Use "onChangeText" or "onChange" instead.'),
                            t && Object.keys(t).forEach((function(e) {
                                    -1 === v.VALID_OPTIONS.indexOf(e) && console.warn('Unknown option "' + e + '". This option will be ignored')
                                }
                            ))),
                            arguments.length && this._create(e, t, n)
                        }
                                                        function y(e, t) {
                                    return function(e) {
                                        if (Array.isArray(e))
                                            return e
                                    }(e) || function(e, t) {
                                        var n = null == e ? null : "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
                                        if (null != n) {
                                            var i, o, s = [], r = !0, a = !1;
                                            try {
                                                for (n = n.call(e); !(r = (i = n.next()).done) && (s.push(i.value),
                                                !t || s.length !== t); r = !0)
                                                    ;
                                            } catch (e) {
                                                a = !0,
                                                    o = e
                                            } finally {
                                                try {
                                                    r || null == n.return || n.return()
                                                } finally {
                                                    if (a)
                                                        throw o
                                                }
                                            }
                                            return s
                                        }
                                    }(e, t) || b(e, t) || function() {
                                        throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
                                    }()
                                }
                                                                function w(e, t) {
                                    var n, i, o, s, r = "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
                                    if (r)
                                        return i = !(n = !0),
                                            {
                                                s: function() {
                                                    r = r.call(e)
                                                },
                                                n: function() {
                                                    var e = r.next();
                                                    return n = e.done,
                                                        e
                                                },
                                                e: function(e) {
                                                    i = !0,
                                                        o = e
                                                },
                                                f: function() {
                                                    try {
                                                        n || null == r.return || r.return()
                                                    } finally {
                                                        if (i)
                                                            throw o
                                                    }
                                                }
                                            };
                                    if (Array.isArray(e) || (r = b(e)) || t && e && "number" == typeof e.length)
                                        return r && (e = r),
                                            s = 0,
                                            {
                                                s: t = function() {}
                                                ,
                                                n: function() {
                                                    return s >= e.length ? {
                                                        done: !0
                                                    } : {
                                                        done: !1,
                                                        value: e[s++]
                                                    }
                                                },
                                                e: function(e) {
                                                    throw e
                                                },
                                                f: t
                                            };
                                    throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
                                }

                         function v(e, t, n) {
                                                e.preventDefault(),
                                                    n.set(t.get())
                                            }
                          async function y(e, t) {
                                                let n;
                                                e.preventDefault(),
                                                    [n] = await window.showOpenFilePicker();
                                                const i = await n.getFile()
                                                    , o = await i.text();
                                                t.setText(o)
                                            }
                                            async function w(e, t) {
                                                e.preventDefault();
                                                const n = await window.showSaveFilePicker({
                                                    types: [{
                                                        description: "JSON Files",
                                                        accept: {
                                                            "text/plain": [".json"]
                                                        }
                                                    }]
                                                })
                                                    , i = await n.createWritable();
                                                await i.write(t.getText()),
                                                    await i.close()
                                            }